<template>
    <view class="container" v-if="sectionDatail">
        <video-component :data="videoData" v-if="videoData&&sectionDatail.contentType==1"></video-component>
        <image  v-if='sectionDatail.contentType==4' :src="sectionDatail.banner" class="section_banner"></image>
        <view class="section_detail">
            <view class="section_base_data">
                <text class="section_title">{{sectionDatail.title}}</text>
                <!-- <view class="section_base_bottom">
                    <text class="class_num" v-if="sectionDatail.contentType==1">视频</text>
                    <text class="class_num" v-if="sectionDatail.contentType==2">直播</text>
                    <text class="class_num" v-if="sectionDatail.contentType==3">音频</text>
                    <text class="class_num" v-if="sectionDatail.contentType==4">图文</text>
                    <text class="dot">·</text>
                    <text class="update_time">{{sectionDatail.endTime}}更新</text>
                </view> -->
                <!-- <view class="belong_course_block" :data-url="'course_detail.html?instanceId='+sectionDatail.belongCourseInstanceId" @tap="tolinkUrl">
                    <view class="belong_course_left">
                        <view class="belong_course_info">
                            <text class="belong_course_text">来自</text>
                            <text class="belong_course_title">{{sectionDatail.belongCourseTitle}}</text>
                        </view>
                    </view>
                    <image class="belong_course_icon" src="https://image1.sansancloud.com/xianhua/2020_1/2/18/38/31_120.jpg?x-oss-process=style/preview_120"></image>
                </view> -->
                <!-- <text class="section_description">
                    {{sectionDatail.description}}
                </text> -->
            </view>
            <view class="servant_info_block" v-if="sectionDatail.servant">
                <text class="servant_name">{{sectionDatail.servant.name}}</text>
                <view class="servant_base_info">
                    <text class="servant_description">{{sectionDatail.servant.description}}</text>
                    <image :src="sectionDatail.servant.icon" mode="aspectFill" class="servant_icon"></image>
                </view>
            </view>
            <view class="section_info_block">
                <view class="section_info_item">
                    <image src="https://image1.sansancloud.com/xianhua/2020_4/26/15/37/33_799.jpg?x-oss-process=style/preview_120" class="section_info_item_icon"></image>
                    <view class="section_info_item_value">
                        <text class="section_info_item_value_item">{{sectionDatail.week}}</text>
                        <text class="section_info_item_value_item">{{sectionDatail.monthDay}}</text>
                        <text class="section_info_item_value_item">{{sectionDatail.timeRang}}</text>
                    </view>
                </view>
                <view class="section_info_item" style="align-items: flex-start;">
                    <image style="margin-top: 4rpx;" src="https://image1.sansancloud.com/xianhua/2020_4/26/17/22/51_490.jpg?x-oss-process=style/preview_120" class="section_info_item_icon"></image>
                    <view class="section_info_item_value" style="flex-direction: column;">
                        <text style="color: #a5c1dd;" @click="navigationToMap(belongMendianDetail)">{{sectionDatail.belongMendianName||'暂无门店'}}（{{belongMendianDetail.distance||0}}km）</text>
                        <text v-if="belongMendianDetail">
                            {{belongMendianDetail.address}}
                        </text>
                    </view>
                </view>
                <view class="section_info_item">
                    <image src="https://image1.sansancloud.com/xianhua/2020_4/26/15/37/17_30.jpg?x-oss-process=style/preview_120" class="section_info_item_icon"></image>
                    <view class="section_info_item_value">
                        <text v-if="sectionDatail.sectionPrice>0">￥{{sectionDatail.sectionPrice}}</text>
                        <text v-else>免费</text>
                    </view>
                </view>
            </view>
            <view class="section_introduction_block">
                <text class="section_introduction_title">课程简介</text>
                <text class="section_introduction_value">{{sectionDatail.description}}</text>
            </view>
        </view>
        <view class="section_blcok" v-if="sectionDatail.contentType==4">
            <view class="section_rich">
                <rich-text-component :receiveData="articleJsonData" v-if="articleJsonData"></rich-text-component>
            </view>
        </view>
        <view class="section_btn_list" v-if="sectionDatail.userBuyed==0">
            <view class="add_section_btn" :style="{background:defaultColor}" @click="confirmReserve">
                <text class="add_section_btn_text">立即预约</text>
                <!-- <text class="add_section_price">￥{{sectionDatail.sectionPrice}}</text> -->
            </view>
        </view>
    </view>
</template>

<script>
import { socketFun } from "../../wxcomponents/public/json2Form";
export default {
  data() {
    return {
      sectionDatail:null,
      secondColor:'',
      defaultColor:'',
      params:{},
      articleJsonData:'',
      videoData:'',
      belongMendianDetail:null,
    };
  },
  props: {},

  /*onload*/
  onLoad: function (options) {
    let that=this;
    console.warn("======onLoad:options======", options, getApp().globalData.setting);
    that.params=options;
    that.getSectionData(options);
  },
  onReady: function () {
    
  },
  onShow: function () {
    let that=this;
	that.setData({
        setting:getApp().globalData.setting,
        defaultColor:getApp().globalData.setting.platformSetting.defaultColor,
        secondColor:getApp().globalData.setting.platformSetting.secondColor,
       })
  },
  /* 分享 app.js862行*/
  onShareAppMessage: function () {
    console.log(getApp().globalData.miniIndexPage);
    return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
  },
  onPullDownRefresh: function () {
    let that = this; // 下拉刷新的时候首先判断存不存在tab
    console.log("下拉");
    that.getsectionData(that.params);
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    let that = this
  },
  onPageScroll: function (object) {
      let that=this;
      // that.setData({
      //   scroll: object.scrollTop
      // })
  },
  methods: {
      /* 确认预定课程 */
      confirmReserve: function () {
        let that = this;
        console.log("=====confirmReserve========",that.sectionDatail);
        let params = {
          instanceId : that.sectionDatail.belongCourseInstanceId,
          sectionId:that.sectionDatail.id,
        };
        var customIndex = getApp().globalData.AddClientUrl('/wx_create_course_pay_order.html', params, 'post');
        getApp().globalData.showToastLoading('loading', true);
        wx.request({
          url: customIndex.url,
          data: customIndex.params,
          header: getApp().globalData.headerPost,
          method: 'POST',
          success: function (res) {
            console.log("=====confirmReserve_res======", res.data);
      
            if (res.data.errcode == 0) {
                let url='edit_order.html?orderNo=' + res.data.relateObj.orderNo
                that.tolinkUrl(url)
            }
      
            wx.hideLoading();
          },
          fail: function (res) {
            console.log("fail");
            wx.hideLoading();
            getApp().globalData.loadFail();
          },
          complete: function () {}
        });
      },
    /* 获取数据 */
    getSectionData: function (params) {
      var that = this
      var customIndex = getApp().globalData.AddClientUrl("/wx_get_course_section_detail.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj
          if (!data ) {
            that.setData({ sectionDatail: {} })
          } else {
             data.endTimeStr=data.endTime.slice(0,11)
             data.startTimeStr=data.startTime.slice(0,11)
             let startTimeDate = new Date(data.startTime.replace(/-/g,  "/"));
             let endTimeDate = new Date(data.endTime.replace(/-/g,  "/"));
             let curDayData = startTimeDate.getDay();
             console.log("===curDayData===",curDayData)
             if(curDayData==0){
                data.week='周日'
             }else if(curDayData==1){
                data.week='周一'
             }else if(curDayData==2){
                data.week='周二'
             }else if(curDayData==3){
                data.week='周三'
             }else if(curDayData==4){
                data.week='周四'
             }else if(curDayData==5){
                data.week='周五'
             }else if(curDayData==6){
                data.week='周六'
             }
             data.monthDay=that.isZero(startTimeDate.getMonth() + 1) + '月' + that.isZero(startTimeDate.getDate())+'日';
             data.timeRang=that.isZero(startTimeDate.getHours()) + ':' + that.isZero(startTimeDate.getMinutes()) +'-'+that.isZero(endTimeDate.getHours()) + ':' + that.isZero(endTimeDate.getMinutes())
             let articleJsonData='';
             if (data.content) {
                articleJsonData=data.content;
             }else if(data.section&&data.section.content){
                 articleJsonData=data.section.content||''
             }
             console.log('====articleJsonData====', articleJsonData);
            that.setData({
              articleJsonData: {jsonData:{content:articleJsonData}}
            });
            if(data.belongMendianId){
                that.gainMenDianDetail(data.belongMendianId);
                that.gainLivePlayerRooms()
            }
            if(data.contentType!=4){
                that.setData({
                  videoData: {jsonData:{source:data.streamMedia,autoPlay:"0"}}
                });
            }
            console.log("videoData",that.videoData,data)
            that.setData({ sectionDatail: data })
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    navigationToMap:function(itemData){
        getApp().globalData.navigationToMap(itemData)
    },
    // 默认门店获取数据
    gainMenDianDetail: function (mendianId) {
      console.log("======a=======")
      var that = this
      let menDian = {
        mendianId: mendianId,
      }
      let menDianYangShi = getApp().globalData.AddClientUrl("/mendian_detail.html", menDian, 'get')
      wx.getLocation({
        type: 'gcj02',
        success: function (item) {
          let latitude = item.latitude;
          let longitude = item.longitude;
          console.log(latitude);
          wx.request({
            url: menDianYangShi.url,
            data: menDianYangShi.params,
            header: getApp().globalData.headerPost,
            method: 'get',
            success: function (res) {
              console.log("======a=======", res)
              let data=res.data.relateObj;
              if (res.data.errcode == "-1") {
                wx.showToast({
                  title: res.data.errMessage,
                  image: '/wxcomponents/images/icons/tip.png',
                  duration: 2000
                })
              }
              else {
                // 直接拿到arr数据，放到wxml中去渲染
                data.distance = getApp().globalData.getDistance(latitude, longitude, data.latitude, data.longitude).toFixed(1);
                that.setData({
                  belongMendianDetail: data,
                })
              }
            }
          })
        }
      })
    },
    gainLivePlayerRooms: function () {
      console.log("======a=======")
      var that = this
      let menDianYangShi = getApp().globalData.AddClientUrl("/wx_find_mini_live_player_rooms.html", '', 'get')
      wx.request({
        url: menDianYangShi.url,
        data: menDianYangShi.params,
        header: getApp().globalData.headerPost,
        method: 'get',
        success: function (res) {
          console.log("======a=======", res)
          let data=res.data.relateObj;
          if (res.data.errcode == "-1") {
            wx.showToast({
              title: res.data.errMessage,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            })
          }
          else {
            
          }
        }
      })
    },
    isZero:function (m){
        return m<10?'0'+m:m
    },
    /* 组件事件集合 */
    tolinkUrl: function (e) {
      console.warn("=======e=======", e);
      let linkUrl = e.currentTarget?e.currentTarget.dataset.url:e;
      getApp().globalData.linkEvent(linkUrl);
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>